/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.bootstrap;

import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Bootstrap {
    private static Connector connector;
    private static ApplicationContext applicationContext;
    public static final Logger log = LoggerFactory.getLogger(Bootstrap.class);

    public static void setConnector(Connector connector) {
        Bootstrap.connector = connector;
    }

    public static ApplicationContext applicationContext() {
        return Bootstrap.applicationContext;
    }

    public static ApplicationContext start(Class<?> clazz, String[] args) {
        try {
            Bootstrap.applicationContext = SpringApplication.run(clazz, args);
            Runtime.getRuntime().addShutdownHook(new Thread(Bootstrap::gracefullyExit));
        } catch (Throwable e) {
            log.error("run server error", e);
            System.exit(-1);
        }
        return applicationContext();
    }

    public static void exit(){
        SpringApplication.exit(applicationContext);
    }

    private static void gracefullyExit() {
        connector.pause();
        Executor executor = connector.getProtocolHandler().getExecutor();
        log.info("Tomcat thread pool: {}", executor);
        if (executor instanceof ThreadPoolExecutor) {
            try {
                int pauseServer = 1000, waitTime = 10;
                Thread.sleep(pauseServer);
                ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
                threadPoolExecutor.shutdown();
                if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {
                    log.warn("Tomcat thread pool did not shut down gracefully within " + waitTime + " seconds. Proceeding with forceful shutdown");
                }
            } catch (InterruptedException ex) {
                log.error("InterruptedException", ex);
                Thread.currentThread().interrupt();
            }
        }
    }
}
